<template lang="pug">
  .zgplugin-table-list.zgplugin-empty(v-if="(!exist || !show)&&editor")
    svg-icon.empty-icon(icon-class="组件自配列表")
  el-form-item.zgplugin-table-list(v-show="show" v-else-if="exist" label-width="0px" :prop="config.propertyName" :rules="rules")
    div(style="display:flex")
      requiredLabel(:required="required" :label="config.label" style="flex:1")
      van-button.float-right(style="min-width:50px;" type="info" size="small" :disabled="readonly" :nativeType="'button'" @click="addRow" v-if="isShowAddButton") 增加
    ul
      li.table-list-li(v-for="(item ,index) in mobileList" @click="item._extend = !item._extend")
        van-row
          div.pr-2.pl-2(style="display:flex;")
            div(style="height:20px;width:20px;border-radius: 50%;border:1px solid #ccc;display:inline-block;color:#333;text-align:center;vertical-align:middle;margin-right:4px;line-height:20px;") {{index + 1}}
            span.app-title(style="line-height:22px;") {{row(config.titleShowExp, item)}}
            .svg-icon-group(style="display:inline-block;margin-left:4px;")
              svg-icon(:icon-class="item._extend?'arrow-up':'arrow-down'").float-right.ml-3
              svg-icon(icon-class="删除" @click.native.stop="deleteRow(index)" v-show="!readonly&&!item._readonly").float-right
              svg-icon(icon-class="编辑" v-show="!readonly&&!item._readonly" @click.native.stop="editRow(item)").float-right.mr-3
        van-row.pr-2.pl-2(v-show="item._extend")
          van-row(style="display:flex;color:#999999;line-height:22px;padding:5px 0;color:#999999;margin-left:26px;" v-for="option in config.options")
            span {{option.label+" ："}}
            div(style="flex:1") {{item[option.config.propertyName]}}
    van-dialog.w-100.h-100.table-list-dialog(v-model="dialogShow" v-if="dialogShow" :overlay="false" :show-confirm-button="false")
      .dialog-title
        van-icon.dialog-title-content.float-left(name="cross" @click="dialogShow=false")
        span.dialog-title-content.float-right(@click="dialogSubmit") 确 定
      .dialog-content
        component(style="margin-top:0;" v-for="(item,index) in config.options" :is="item.type + 'PluginRender'" :readonlyMain="readonly" :editor="editor" :config="item.config" :scope='dialogData' :ref="'dialog_'+index+item.config.propertyName")

</template>
<script>
import inputPluginRender from '../../input/APP/render'
import selectPluginRender from '../../select/APP/render'
import datePluginRender from '../../date/APP/render'

import inputCommon from '../../../../mixin/inputCommon'
import requiredLabel from '../../../../components/requiredLabel'
import _ from 'lodash'
import { invokeInterface } from '../../../../service'
import { addCSSWithId, addPrefixToCssText, removeElementBySelector } from '../../../../utils/domUtil'

export default {
  name: 'render',
  props: ['config', 'editor'],
  inject: ['rootForm'],
  mixins: [inputCommon],
  components: { inputPluginRender, selectPluginRender, datePluginRender, requiredLabel },
  data() {
    return {
      default: [],
      dialogShow: false,
      editFlag: false,
      currentEditData: {},
      dialogData: {},
      mobileList: _.map(_.cloneDeep(this.rootForm.properties[this.config.propertyName]), one => {
        one._extend = false
        return one
      }),
      appTitleId: _.uniqueId('appTitleId')
    }
  },
  computed: {
    isShowAddButton() {
      if (!this.config.isShowAddButton && this.config.isShowAddButton !== false) {
        return true
      }
      return !!this.getParsedEx('isShowAddButton')()
    }
  },
  watch: {
    mobileList: {
      handler() {
        this.rootForm.properties[this.config.propertyName] = _.cloneDeep(this.mobileList)
        this.rootForm.properties[this.config.propertyName].forEach((one, index) => {
          delete one._extend
          this.$nextTick(() => {
            if (this.$el) {
              this.$el.querySelectorAll('.app-title')[index].classList.add(this.appTitleId)
            }
          })
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    row(item, scopeRow) {
      return (new Function('$data', '$row', 'with($data) {return ' + item + '}'))(this.rootForm.properties, scopeRow)
    },
    initDailogData() {
      let obj = {}
      _.each(this.config.options, one => {
        obj[one.config.propertyName] = undefined
      })
      this.dialogData = obj
    },
    addRow() {
      this.editFlag = false
      this.dialogShow = true
      this.initDailogData()
    },
    deleteRow(index) {
      this.mobileList.splice(index, 1)
    },
    editRow(item) {
      this.editFlag = true
      this.dialogShow = true
      this.initDailogData()
      this.dialogData = _.cloneDeep(item)
      this.currentEditData = item
    },
    validateDialog() {
      let res = true
      this.config.options.forEach((one, index) => {
        if (this.$refs['dialog_' + index + one.config.propertyName] && this.$refs['dialog_' + index + one.config.propertyName][0].validate() !== true) {
          res = false
        }
      })
      return res
    },
    dialogSubmit() {
      if (this.validateDialog()) {
        if (this.editFlag) {
          Object.assign(this.currentEditData, this.dialogData)
        } else {
          this.$set(this.dialogData, '_extend', false)
          this.mobileList.push(this.dialogData)
        }
        this.dialogShow = false
      } else {
        return false
      }
    },
    initData() {
      if (this.config.initConnectType === 'interface' && this.config.dataInterfaceId) {
        this.linkSearchExVal = this.getParsedEx('linkSearchEx')()
        let params = { }
        if (this.config.linkSearch) {
          let v = this.getParsedEx('linkSearchEx')()
          if (v !== 0) {
            v = v || ''
          }
          params[this.config.linkSearchQueryKey] = v
          if (!v) {
            return 
          }
        }
        this.initLoading = true
        invokeInterface(this.config.dataInterfaceId, params).then(data => {
          this.rootForm.properties[this.config.propertyName] = _.uniqWith(this.rootForm.properties[this.config.propertyName].concat(data), _.isEqual)
          this.mobileList = _.map(_.cloneDeep(this.rootForm.properties[this.config.propertyName]), one => {
            one._extend = false
            return one
          })
        }).finally(() => {
          this.initLoading = false
        })
      } else if (this.config.initConnectType === 'customGetter' && this.config.customGetter) {
        let initData = this.getParsedFn('customGetter')() || []
        this.rootForm.properties[this.config.propertyName] = _.uniqWith(this.rootForm.properties[this.config.propertyName].concat(initData), _.isEqual)
        this.mobileList = _.map(_.cloneDeep(this.rootForm.properties[this.config.propertyName]), one => {
          one._extend = false
          return one
        })
      }
    }
  },
  beforeDestroy() {
    // 清除自定义样式
    removeElementBySelector('#' + this.appTitleId)
  },
  created() {
    // 初始化数据 数据字典
    if (!this.rootForm.properties['__noInitData' + this.config.propertyName] && this.config.initConnectType) {
      this.initData()
      this.rootForm.properties['__noInitData' + this.config.propertyName] = true
    }
    // 关联值变化了  初始化数据刷新
    if (this.config.initConnectType === 'interface' && this.config.dataInterfaceId && this.config.linkSearch) {
      this.$watch(this.getParsedEx('linkSearchEx'), (newValue) => {
        this.rootForm.properties[this.config.propertyName] = []
        this.initData()
      })
    } else if (this.config.initConnectType === 'customGetter' && this.config.customGetter) {
      this.$watch(this.getParsedFn('customGetter'), (newValue) => {
        this.rootForm.properties[this.config.propertyName] = []
        this.initData()
      })
    }
    if (this.config.titleStyle) {
      addCSSWithId(addPrefixToCssText(this.config.titleStyle, '.' + this.appTitleId), this.appTitleId)
    }
    // _.forEach(this.config.options, one => {
    //   if (!one.config.label) {
    //     one.config.label = one.label
    //   }
    // })
  }
}
</script>
<style lang="scss">
  .zgplugin-table-list {
    .table-list-dialog {
      border-radius: 0px !important;
      > .van-dialog__content {
        height: 100%;
        max-height: 100%;
        overflow: hidden;
        padding: 0 !important;
      }
      .dialog-title {
        height: 50px;
        background: #1976d2 !important;
        color: #fff;
        padding: 0 20px;
        font-size: 18px;
        .dialog-title-content {
          padding: 0 20px;
          line-height: 50px;
        }
      }
      .dialog-content {
        height: calc(100% - 60px);
        overflow: auto;
        padding: 10px 20px 0;
      }
    }
  }
</style>
<style lang="scss" scoped>
  .zgplugin-table-list {
    margin-bottom: 0px !important;
    margin-top: 16px;
    .table-list-dialog {
      .dialog-title {
        line-height: 50px;
        background: #1976d2 !important;
        color: #fff;
        padding: 0 20px;
        font-size: 18px;
      }
    }
    .table-list-li {
      padding: 10px 0;
      border-bottom: 1px solid #ccc;
      .app-title {
        flex: 1;
      }
      .svg-icon-group {
        // padding-top: 8px;
        .svg-icon {
          font-size: 20px;
          color: #6E3CCA;
        }
      }
    }
  }
</style>
